算法Java程序从列表中给定的数字中分组连续数<list>
假设你得到了唯一的数字,比如
11,2,7,6,17,13,8,9,3,5,12
结果将是一组包含子列表的数字列表,即:
[2,3]-[5,6,7,8,9]-[11,12,13]-[17]
我采用这种方法来解决以下问题:
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> ListMain = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i + 1] == a[i] + 1) {
temp.add(a[i + 1]);
} else {
ListMain.add(temp);
temp.clear();
}
}
# 1 楼答案
谢谢Garis M Suero的建议,之后我得到了答案